package cc.owoo.godpen.analysis.css;

import cc.owoo.godpen.analysis.html.Element;
import cc.owoo.godpen.analysis.html.ElementList;

import java.util.Queue;

/**
 * class选择器
 * Created by nimensei
 * 2022-06-01 上午 12:40
 */
public class ClassSelector extends SelectorNode {
    private final String className;// class名称

    /**
     * 创建一个class选择器节点
     *
     * @param className class名称，不能为空和为null
     */
    public ClassSelector(String className) {
        if (className == null || (className = className.trim().toLowerCase()).length() == 0)
            throw new NullPointerException("className不能为空");
        this.className = className;
    }

    @Override
    void selectElement(Element element, Queue<Element> elements) {
        ElementList elementList = element.getElementsByClassName(className);
        if (elementList.size() == 0)
            return;
        for (Element child : elementList)
            elements.add(child);
    }

    @Override
    void matchingElement(Element element, Queue<Element> elements) {
        String elementClassName = element.getClassName();
        if (elementClassName == null || !elementClassName.equals(className))
            return;
        elements.add(element);
    }

    @Override
    public void stringify(StringBuilder string) {
        string.append('.').append(className);
    }
}
